package org.lee.myshiroredisplus.shiro;

import org.crazycake.shiro.IRedisManager;
import org.crazycake.shiro.common.WorkAloneRedisManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author jackielee
 * @version 1.0
 * @description RedisManager
 * @date 2021/4/9
 */
public class RedisManager extends WorkAloneRedisManager implements IRedisManager {
  private RedisProperties redis;
  private JedisPool jedisPool;

  @Value("${spring.redis.host}")
  private String host;
  @Value("${spring.redis.port}")
  private int port;
  @Value("${spring.redis.timeout}")
  private int timeout;
  @Value("${spring.redis.password}")
  private String password;
  @Value("${spring.redis.database}")
  private int database;

  public RedisManager(RedisProperties redis) {
    this.redis = redis;
  }

  private void init() {
    synchronized (this) {
      if (this.jedisPool == null) {
        this.jedisPool =
            new JedisPool(
                this.getJedisPoolConfig(),
                host,
                port,
                timeout,
                password,
                database);
      }
    }
  }

  @Override
  protected Jedis getJedis() {
    if (jedisPool == null) {
      this.init();
    }
    return jedisPool.getResource();
  }
}
